package drds.plus.executor.repository;

import drds.plus.common.model.RepositoryType;
import drds.tools.$;
import drds.tools.ShouldNeverHappenException;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class RepositoryNameToRepositoryMap {
    @Setter
    @Getter
    private Map<String, Repository> repositoryTypeToRepositoryMap = new ConcurrentHashMap<String, Repository>();


    public Repository getRepository(String repositoryType, Map<String, String> properties, Map connectionProperties) {
        if (repositoryTypeToRepositoryMap.get(repositoryType) == null) {
            return repositoryTypeToRepositoryMap.get(repositoryType);
        }
        synchronized (this) {
            if (repositoryTypeToRepositoryMap.get(repositoryType) == null) {
                IRepositoryFactory repositoryFactory = newInstance(repositoryType);
                Repository repository = repositoryFactory.buildRepository(properties, connectionProperties);
                try {
                    repository.init();
                } catch (RuntimeException e) {
                    throw e;
                }
                repositoryTypeToRepositoryMap.put(repositoryType, repository);
            }
        }

        return repositoryTypeToRepositoryMap.get(repositoryType);
    }

    private IRepositoryFactory newInstance(String repositoryType) {
        if (RepositoryType.mysql.name().equals(repositoryType)) {
            try {
                return (IRepositoryFactory) Class.forName(IRepositoryFactory.mysql_repository_factory).newInstance();
            } catch (Exception e) {
                log.error("实例化mysql存储工厂失败", $.printStackTraceToString(e));
                throw new IllegalStateException(e);
            }
        } else if (RepositoryType.bdb.name().equals(repositoryType)) {
            try {
                return (IRepositoryFactory) Class.forName(IRepositoryFactory.berkeley_repository_factory).newInstance();
            } catch (Exception e) {
                log.error("实例化mysql存储工厂失败", $.printStackTraceToString(e));
                throw new IllegalStateException(e);
            }
        } else {
            throw new ShouldNeverHappenException();
        }

    }


}
